package com.banciyuan.bcywebview.biz.zanlist;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.SpaceApi;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreashRecycleView;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.recycleview.OnResultScrollListener;
import com.banciyuan.bcywebview.biz.zanlist.decoration.ZanItemOffsetDecoration;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.ZanListItem;

/**
 * Created by hy on 2015/4/28.
 */
public class ZanListFragment extends BaseLazyContainerFragment {

    private PullToRefreashRecycleView mRefreshRv;
    private RecyclerView mContentRv;
    private RequestQueue mQueue;
    private List<ZanListItem> list = new ArrayList<>();
    private String sub = "coser";
    private View mProgressbarView;
    private ProgressbarHelper mProgressbarHelper;
    private int page = 1;
    private boolean loading = false;
    private boolean hasMore = true;
    private ZanListAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.zanlist_layout, container, false);
        initProgressbar(rootView);
        initArgs();
        initUi(rootView);
        initAction();
        return rootView;
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(getActivity());
        Bundle bundle = getArguments();
        sub = bundle.getString("sub");
    }

    @Override
    protected void initProgressbar(View rootview) {
        mProgressbarView = rootview.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(rootview);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                hasMore = true;
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi(View rootview) {
        mRefreshRv = (PullToRefreashRecycleView) rootview.findViewById(R.id.recleview);
        mContentRv = mRefreshRv.getRefreshableView();

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return position == 0 ? 3 : 1;
            }
        });
        mContentRv.addItemDecoration(new ZanItemOffsetDecoration(UIUtils.dip2px(4, getActivity())));
        mContentRv.setLayoutManager(gridLayoutManager);
        adapter = new ZanListAdapter(getActivity(), list);
        mContentRv.setAdapter(adapter);
    }

    @Override
    protected void initAction() {

        mContentRv.addOnScrollListener(new OnResultScrollListener() {
            @Override
            public void onBottom() {
                if (!loading && hasMore) {
                    page++;
                    initData();
                }
            }
        });

        mRefreshRv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<RecyclerView>() {
            @Override
            public void onRefresh(PullToRefreshBase<RecyclerView> refreshView) {
                page = 1;
                loading = false;
                hasMore = true;
                initData();
            }
        });
    }

    @Override
    protected void initData() {
        loading = true;
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        paramsList.add(new BcyPair(HttpUtils.COMENT_SUB, sub));
        paramsList.add(new BcyPair(HttpUtils.INDEX_P, page + ""));
        final HashMap<String, String> params = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + SpaceApi.getZanlist();
        Response.Listener onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Gson gson = new Gson();
                try {
                    if (StatusCodeUtils.dealStatusCode(s, getActivity())) {
                        JSONObject result = new JSONObject(s);
                        List<ZanListItem> tempList = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA),
                                new TypeToken<List<ZanListItem>>() {
                                }.getType());
                        processFinalData(tempList);
                    } else {
                        loading = false;
                        mProgressbarHelper.onFailed();
                        mRefreshRv.onRefreshComplete();
                    }
                } catch (Exception e) {
                    loading = false;
                    mProgressbarHelper.onFailed();
                    mRefreshRv.onRefreshComplete();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mRefreshRv.onRefreshComplete();
                mProgressbarHelper.onFailed();
                loading = false;
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSuccess, url, getActivity(), params);
        StringRequest stringRequest = new StringRequestParam(Request.Method.POST, url, params, onSuccess, errorProxy);
        mQueue.add(stringRequest);
    }


    private void processFinalData(List<ZanListItem> templist) {
        if (page == 1) {
            list.clear();
        }
        if (templist.size() == 0) {
            hasMore = false;
        }
        int start = list.size();
        list.addAll(templist);
        if (null == adapter) {
            adapter = new ZanListAdapter(getActivity(), list);
            mContentRv.setAdapter(adapter);
        } else {
            if (page == 1) {
                adapter.notifyDataSetChanged();
            } else {
                adapter.notifyItemRangeInserted(start + 1, list.size() - start);
            }
        }
        loading = false;
        mProgressbarHelper.onSuccess();
        mRefreshRv.onRefreshComplete();
    }

}
